package wymiana.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import wymiana.service.AuthoritiesService;
//import wymiana.service.CarService;
import wymiana.service.UserService;

@Controller
@RequestMapping(value = "/quick/*")
public class QuickSearchController {

	// private static final String MSGKEY = "message";

	@Autowired
	UserService userService;

	@Autowired
	AuthoritiesService authService;

//	@Autowired
//	private CarService carService;

	public static class QueryResult {
		private String label;
		private String id;
		private String verId;

		public QueryResult(String label, String id, String verId) {
			this.label = label;
			this.id = id;
			this.verId = verId;
		}

		public String getLabel() {
			return label;
		}

		public String getId() {
			return id;
		}

		public String getVerId() {
			return verId;
		}
	}

	@RequestMapping(value = "/show.do")
	public String register() {
		return "quickSearch";
	}

	@RequestMapping(value = "/query.do")
	public String query() {
		return "quickSearch";
	}

	private List<QueryResult> doQuery(String term, final int LIMIT) {

//		ArrayList<Object[]> cars = (ArrayList<Object[]>) carService
//				.getCarSearch(term, LIMIT);

		List<QueryResult> result = new ArrayList<QueryResult>();
//		for (Object[] car : cars) {
//			result.add(new QueryResult(car[0].toString() + " "
//					+ car[1].toString() + " " + car[2].toString() + " "
//					+ car[3].toString(), car[4].toString(), car[1].toString()));
//		}
		return result;
	}

	@RequestMapping(value = "query.do", method = RequestMethod.GET)
	public void query(HttpServletResponse response, @RequestParam String term)
			throws IOException {
		final int LIMIT = 10;

		List<QueryResult> result = doQuery(term, LIMIT);
		String json = JSONArray.fromObject(result).toString();

		response.setCharacterEncoding("UTF-8");
		response.addHeader("Cache-Control", "no-cache");
		response.getWriter().print(json);
		response.getWriter().close();
	}

}
